/*
 * ECARX Technology Limited is the owner of the copyright and the trade secret of this software.
 * Without permission, no one has the right to obtain, disclose or use this software in any way.
 */
package com.ecarx.systemui.plugin.ui.custom

import android.content.Context
import android.net.wifi.WifiInfo
import android.net.wifi.WifiManager
import android.util.AttributeSet
import android.util.Log
import android.view.LayoutInflater
import android.widget.FrameLayout
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.ecarx.systemui.plugin.PluginContext
import com.ecarx.systemui.plugin.R
import com.ecarx.systemui.plugin.controller.IWifiItemData
import com.ecarx.systemui.plugin.controller.TcamWifiController
import com.ecarx.systemui.plugin.controller.WifiItemData
import com.ecarx.systemui.plugin.controller.WifiItemNothing
import com.ecarx.systemui.plugin.controller.WifiItemTitleOther
import com.ecarx.systemui.plugin.controller.WifiItemTitlePreferred
import com.ecarx.systemui.plugin.ui.adapter.WifiItemAdapter
import com.ecarx.systemui.plugin.ui.dialog.base.DialogManager
import com.ecarx.systemui.plugin.utils.AppUtils
import com.ecarx.systemui.plugin.utils.LogUtils
import ecarx.openapi.net.wifi.StaConnectionListener
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class WifiListView : FrameLayout {
    companion object {
        private const val TAG = "WifiListView"
    }

    private var mSwitch: CustomSwitch? = null
    private var mRecyclerView: RecyclerView? = null
    private var mAdapter: WifiItemAdapter? = null
    private var mData: MutableList<IWifiItemData>? = null
    constructor(context: Context?) : this(context!!, null) {}
    constructor(context: Context?, attrs: AttributeSet?) : this(
        context!!, attrs, 0
    ) {}

    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context!!, attrs, defStyleAttr
    ) {
        init()
    }

    private fun init() {
        LayoutInflater.from(context).inflate(
            R.layout.cust_view_layout_wifi,
            this, true
        )
        mSwitch = findViewById<CustomSwitch>(R.id.custom_switch)
        mSwitch?.setSwitchChangeListener(object : CustomSwitch.SwitchChangeListener {
            override fun toClose() {
                enableWifi(enable = false, changeSwitch = false)

            }

            override fun toOpen() {
                enableWifi(enable = true, changeSwitch = false)
            }

        })
        mRecyclerView = findViewById<RecyclerView>(R.id.rv_wifi)

        mData = ArrayList<IWifiItemData>()
        mAdapter = WifiItemAdapter(mData)
        mRecyclerView?.layoutManager = LinearLayoutManager(context)
        mRecyclerView?.adapter = mAdapter
        findViewById<TextView>(R.id.tv_wifi_preferences).setOnClickListener {
            AppUtils.openWifiSettings(context)
        }

        enableWifi(TcamWifiController.isWifiEnabled(),true)
        TcamWifiController.registerWifiStateListener {
            enableWifi(it == WifiManager.WIFI_STATE_ENABLED, true)
        }


        TcamWifiController.registerWifiConnectListener(object : TcamWifiController.ConnectionStatusListener {
            override fun onStateChanged(state: Int, wifiInfo: WifiInfo) {
                LogUtils.d(TAG, "onStateChanged() called with: state = $state, wifiInfo = $wifiInfo")
                updateData()
            }

            override fun onError(code: Int) {
                LogUtils.w(TAG, "onError() called with: code = $code")
                if (code == StaConnectionListener.ERROR_PASSWORD_INCORRECT) {
                    DialogManager.showErrorInfoDialog(context, R.string.pwd_error, R.string.pwd_error_desc)
                } else {
                    Toast.makeText(context, String.format(context.resources.getString(R.string.wifi_connect_error), code), Toast.LENGTH_SHORT).show()
                }
            }

        })

        updateData()
    }

    private fun enableWifi(enable: Boolean, changeSwitch: Boolean){
        LogUtils.d(TAG, "enableWifi() called with: enable = $enable, changeSwitch = $changeSwitch")
        if (changeSwitch) {
            if (enable) {
                mSwitch?.uiOpen()
            } else {
                mSwitch?.uiClose()
            }
        }
        TcamWifiController.setWifiEnabled(enable)

        updateData()
    }

    @Synchronized
    private fun updateData() {
        LogUtils.d(TAG, "updateData() called")
        CoroutineScope(Dispatchers.IO).launch {
            TcamWifiController.getScanWifiList { wifiDataList ->
                mData?.clear()

                val connectionWifi = TcamWifiController.getConnectionWifi()
                if (connectionWifi != null) {
                    mData?.add(WifiItemTitlePreferred())
                    mData?.add(WifiItemData(connectionWifi))
                }
                if (wifiDataList.isNotEmpty()) {
                    mData?.add(WifiItemTitleOther())
                    wifiDataList.forEach { wifiData ->
                        mData?.add(WifiItemData(wifiData))
                    }
                } else {
                    mData?.add(WifiItemNothing())
                }
                LogUtils.d(TAG, "updateData() called: ${mData}")
                CoroutineScope(Dispatchers.Main).launch {
                    mAdapter?.notifyDataSetChanged()
                }

            }
        }
    }
}